/**
 * @file    crc16.c
 * @brief   Implementation of crc.h
 */

#include "bs_crc.h"

#define FALSE	0
#define TRUE	!FALSE

typedef unsigned short  crc;

#define CRC_NAME			"CRC-16"
#define POLYNOMIAL			0x8005
#define INITIAL_REMAINDER	0x0000
#define FINAL_XOR_VALUE		0x0000
#define REFLECT_DATA		FALSE
#define REFLECT_REMAINDER	FALSE
#define CHECK_VALUE			0xBB3D

/*
 * Derive parameters from the standard-specific parameters in crc.h.
 */
#define WIDTH    (8 * sizeof(crc))
#define TOPBIT   (1 << (WIDTH - 1))

#if (REFLECT_DATA == TRUE)
#undef  REFLECT_DATA
#define REFLECT_DATA(X)			((unsigned char) reflect((X), 8))
#else
#undef  REFLECT_DATA
#define REFLECT_DATA(X)			(X)
#endif

#if (REFLECT_REMAINDER == TRUE)
#undef  REFLECT_REMAINDER
#define REFLECT_REMAINDER(X)	((crc) reflect((X), WIDTH))
#else
#undef  REFLECT_REMAINDER
#define REFLECT_REMAINDER(X)	(X)
#endif


//static unsigned long
//reflect(unsigned long data, unsigned char nBits)
//{
//    unsigned long  reflection = 0x00000000;
//    unsigned char  bit;
//    for (bit = 0; bit < nBits; ++bit) {
//        if (data & 0x01) {
//            reflection |= (1 << ((nBits - 1) - bit));
//        }
//        data = (data >> 1);
//    }
//    return (reflection);
//}	


uint16_t
crc16(const void *data, uint32_t nBytes, uint16_t crc_value)
{
    crc            remainder = crc_value;
    int            byte;
    unsigned char  bit;
    unsigned char const *message = data;
    for (byte = 0; byte < nBytes; ++byte) {
        remainder ^= (REFLECT_DATA(message[byte]) << (WIDTH - 8));
        for (bit = 8; bit > 0; --bit) {
            if (remainder & TOPBIT) {
                remainder = (remainder << 1) ^ POLYNOMIAL;
            } else {
                remainder = (remainder << 1);
            }
        }
    }
    return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE);
}
